<template>
  <div class="doctor-home-container">
    <!-- 顶部欢迎栏 -->
    <el-card class="welcome-card">
      <div class="welcome-content">
        <el-avatar :size="80" :src="doctorInfo.img" class="doctor-avatar" />
        <div class="welcome-text">
          <h2>您好, {{ doctorInfo.doc_name || '医生' }}!</h2>
          <p class="subtitle">{{ doctorInfo.doc_title || '职称' }} | {{ departmentName }}</p>
          <p class="date-info">{{ currentDate }}</p>
        </div>
        <div class="quick-stats">
          <div class="stat-item">
            <div class="stat-value">{{ todayAppointmentsCount }}</div>
            <div class="stat-label">今日待接诊</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ announcements.length }}</div>
            <div class="stat-label">最新公告</div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧内容 -->
      <div class="left-column">
        <!-- 今日排班 -->
        <el-card class="schedule-card">
          <template #header>
            <div class="card-header">
              <span>今日排班</span>
            </div>
          </template>
          <div v-if="todaySchedule.amwork || todaySchedule.pmwork" class="schedule-content">
            <div class="time-slot" v-if="todaySchedule.amwork">
              <el-icon><Sunrise /></el-icon>
              <span class="time-range">上午 08:00-12:00</span>
              <el-tag type="success">{{ todaySchedule.amwork }}</el-tag>
            </div>
            <div class="time-slot" v-if="todaySchedule.pmwork">
              <el-icon><Sunset /></el-icon>
              <span class="time-range">下午 14:00-18:00</span>
              <el-tag type="warning">{{ todaySchedule.pmwork }}</el-tag>
            </div>
          </div>
          <div v-else class="empty-schedule">
            <el-empty description="今日无排班" :image-size="60" />
          </div>
        </el-card>
      </div>

      <!-- 右侧内容 - 公告 -->
      <div class="right-column">
        <el-card class="announcement-card">
          <template #header>
            <div class="card-header">
              <span>医院公告</span>
            </div>
          </template>
          <div class="announcement-list">
            <div 
              v-for="item in announcements" 
              :key="item.id" 
              class="announcement-item"
              :class="{ expanded: expandedAnnouncement === item.id }"
            >
              <el-card shadow="hover" class="announcement-content">
                <div 
                  class="announcement-header"
                  @click="toggleAnnouncement(item.id)"
                >
                  <h4>{{ item.title }}</h4>
                  <div class="header-right">
                    <span class="announcement-date">{{ formatDate(item.day) }}</span>
                    <el-icon class="expand-icon">
                      <ArrowDown v-if="expandedAnnouncement !== item.id" />
                      <ArrowUp v-else />
                    </el-icon>
                  </div>
                </div>
                
                <el-collapse-transition>
                  <div v-show="expandedAnnouncement === item.id" class="announcement-details">
                    <div class="announcement-body">
                      <el-image 
                        v-if="item.img" 
                        :src="item.img" 
                        fit="cover" 
                        class="announcement-image"
                      ></el-image>
                      <p class="announcement-text">{{ item.content }}</p>
                    </div>
                    <div class="announcement-footer" v-if="item.author">
                      <span class="announcement-author">发布人: {{ item.author }}</span>
                    </div>
                  </div>
                </el-collapse-transition>
              </el-card>
            </div>
            <div v-if="announcements.length === 0" class="empty-announcements">
              <el-empty description="暂无公告" :image-size="60" />
            </div>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 底部统计 -->
    <el-card class="stats-card">
      <div class="stats-content">
        <div class="stat-chart">
          <h3>本周接诊统计</h3>
          <div class="chart-container">
            <div v-for="day in weeklyStats" :key="day.name" class="chart-day">
              <div class="chart-bar-container">
                <div class="chart-bar" :style="{ height: day.height }"></div>
              </div>
              <div class="chart-label">{{ day.name }}</div>
              <div class="chart-value">{{ day.value }}</div>
            </div>
          </div>
        </div>
        <div class="stat-summary">
          <div class="summary-item">
            <div class="summary-value">{{ weeklyTotal }}</div>
            <div class="summary-label">本周接诊总数</div>
          </div>
          <div class="summary-item">
            <div class="summary-value">{{ avgDaily }}</div>
            <div class="summary-label">日均接诊</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { 
  Sunrise, Sunset, Edit, List, User, ArrowDown, ArrowUp 
} from '@element-plus/icons-vue'
import axios from 'axios'
import { useUserStore } from '@/stores/user'
import dayjs from 'dayjs'

const userStore = useUserStore()

// 医生信息
const doctorInfo = ref({
  doc_name: '',
  doc_title: '',
  img: '',
  depart_id1: null,
  depart_id2: null
})

// 部门名称映射
const departmentMap = {
  1: '内科',
  2: '外科',
  // 其他科室...
}

// 排班信息
const todaySchedule = ref({
  amwork: '',
  pmwork: ''
})

// 公告数据
const announcements = ref([])

// 接诊记录数据
const appointments = ref([])

// 当前展开的公告ID
const expandedAnnouncement = ref(null)

// 计算属性
const currentDate = computed(() => {
  return dayjs().format('YYYY年MM月DD日 dddd')
})

const departmentName = computed(() => {
  return departmentMap[doctorInfo.value.depart_id1] || '未知科室'
})

// 今日待接诊数量
const todayAppointmentsCount = computed(() => {
  const today = dayjs().format('YYYY-MM-DD')
  return appointments.value.filter(app => app.day === today).length
})

// 周统计数据
const weeklyAppointments = computed(() => {
  const startOfWeek = dayjs().startOf('week').format('YYYY-MM-DD')
  const endOfWeek = dayjs().endOf('week').format('YYYY-MM-DD')
  
  return appointments.value.filter(app => {
    return app.day >= startOfWeek && app.day <= endOfWeek
  })
})

const weeklyStats = computed(() => {
  const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  const stats = []
  
  // 初始化一周每天的数据
  for (let i = 0; i < 7; i++) {
    const date = dayjs().startOf('week').add(i, 'day').format('YYYY-MM-DD')
    const count = weeklyAppointments.value.filter(app => app.day === date).length
    stats.push({
      name: weekDays[i],
      date: date,
      value: count
    })
  }
  
  // 计算最大数量用于比例
  const maxCount = Math.max(1, ...stats.map(day => day.value))
  
  // 添加高度属性
  return stats.map(day => ({
    ...day,
    height: `${(day.value / maxCount) * 100}%`
  }))
})

const weeklyTotal = computed(() => {
  return weeklyStats.value.reduce((sum, day) => sum + day.value, 0)
})

const avgDaily = computed(() => {
  const workingDays = weeklyStats.value.filter(day => 
    day.name !== '周日' && day.name !== '周六'
  )
  const total = workingDays.reduce((sum, day) => sum + day.value, 0)
  return workingDays.length > 0 ? (total / workingDays.length).toFixed(1) : 0
})

// 方法
const fetchDoctorInfo = async () => {
  try {
    console.log('正在获取医生信息...')
    const response = await axios.get(
      `http://localhost:8080/hospital5/doctor/findByUserName?user_name=${userStore.userInfo.userName}`
    )
    console.log('医生信息响应:', response.data)
    if (response.data && response.data.length > 0) {
      doctorInfo.value = response.data[0]
      fetchTodaySchedule(doctorInfo.value.doc_id)
      fetchAppointments(doctorInfo.value.doc_id)
    } else {
      console.warn('未获取到医生信息')
    }
  } catch (error) {
    console.error('获取医生信息失败:', error)
  }
}

const fetchTodaySchedule = async (docId) => {
  try {
    console.log('正在获取今日排班...')
    const today = dayjs().format('YYYY-MM-DD')
    const response = await axios.get(`http://localhost:8080/hospital5/doctorWork/findByDocId?docId=${docId}`)
    console.log('排班信息响应:', response.data)
    const todayData = response.data.find(item => item.day === today)
    if (todayData) {
      todaySchedule.value = todayData
    } else {
      console.warn('今日无排班信息')
    }
  } catch (error) {
    console.error('获取排班信息失败:', error)
  }
}

const fetchAppointments = async (docId) => {
  try {
    console.log('正在获取接诊记录...')
    const response = await axios.get(`http://localhost:8080/hospital5/patientDoctor/findByDocId?docId=${docId}`)
    console.log('接诊记录响应:', response.data)
    appointments.value = response.data || []
    if (appointments.value.length === 0) {
      console.warn('无接诊记录数据')
    }
  } catch (error) {
    console.error('获取接诊记录失败:', error)
  }
}

const fetchAnnouncements = async () => {
  try {
    console.log('正在获取公告...')
    const response = await axios.get('http://localhost:8080/hospital5/notice/findAll')
    console.log('公告响应:', response.data)
    announcements.value = response.data || []
    if (announcements.value.length === 0) {
      console.warn('无公告数据')
    }
  } catch (error) {
    console.error('获取公告失败:', error)
  }
}

const formatDate = (dateStr) => {
  return dayjs(dateStr).format('YYYY年MM月DD日')
}

// 切换公告展开状态
const toggleAnnouncement = (id) => {
  expandedAnnouncement.value = expandedAnnouncement.value === id ? null : id
}

// 初始化
onMounted(() => {
  console.log('页面初始化...')
  fetchDoctorInfo()
  fetchAnnouncements()
})
</script>

<style scoped>
.doctor-home-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.welcome-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.doctor-avatar {
  margin-right: 30px;
  border: 3px solid #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.welcome-text {
  flex: 1;
}

.welcome-text h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
  color: #333;
}

.subtitle {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 16px;
}

.date-info {
  margin: 0;
  color: #888;
  font-size: 14px;
}

.quick-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.main-content {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-column {
  flex: 1;
  min-width: 0;
}

.right-column {
  width: 480px;
}

.schedule-card,
.quick-actions-card,
.announcement-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.schedule-content {
  padding: 15px;
}

.time-slot {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.time-slot:last-child {
  margin-bottom: 0;
}

.time-slot .el-icon {
  margin-right: 10px;
  font-size: 18px;
  color: #666;
}

.time-range {
  flex: 1;
  margin-right: 15px;
}

.empty-schedule {
  padding: 30px 0;
  text-align: center;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 15px;
  padding: 15px;
}

.action-button {
  height: 80px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 16px;
}

.action-button .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

/* 公告部分样式 */
.announcement-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.announcement-item {
  transition: all 0.3s;
}

.announcement-content {
  overflow: hidden;
}

.announcement-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  padding: 15px;
  transition: background-color 0.3s;
}

.announcement-header:hover {
  background-color: #f5f7fa;
}

.announcement-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
}

.announcement-date {
  font-size: 12px;
  color: #888;
}

.expand-icon {
  margin-left: 10px;
  font-size: 16px;
  color: #666;
  transition: transform 0.3s;
}

.announcement-details {
  padding: 0 15px 15px 15px;
}

.announcement-body {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.announcement-image {
  width: 100%;
  max-height: 200px;
  border-radius: 4px;
  object-fit: cover;
}

.announcement-text {
  margin: 0;
  color: #666;
  font-size: 14px;
  white-space: pre-line;
  line-height: 1.6;
}

.announcement-footer {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
  font-size: 12px;
  color: #999;
}

.empty-announcements {
  padding: 40px 0;
}

/* 统计卡片样式 */
.stats-card {
  border-radius: 12px;
}

.stats-content {
  display: flex;
}

.stat-chart {
  flex: 1;
  padding-right: 40px;
}

.stat-chart h3 {
  margin-top: 0;
  margin-bottom: 20px;
  color: #333;
}

.chart-container {
  display: flex;
  height: 200px;
  align-items: flex-end;
  justify-content: space-around;
}

.chart-day {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 40px;
}

.chart-bar-container {
  width: 30px;
  height: 150px;
  background-color: #f5f7fa;
  border-radius: 4px;
  position: relative;
  margin-bottom: 10px;
}

.chart-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #409EFF;
  border-radius: 4px;
  transition: height 0.5s ease;
}

.chart-label {
  font-size: 12px;
  color: #666;
}

.chart-value {
  font-size: 14px;
  font-weight: bold;
  margin-top: 5px;
}

.stat-summary {
  width: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  border-left: 1px solid #eee;
  padding-left: 40px;
}

.summary-item {
  text-align: center;
  margin-bottom: 30px;
}

.summary-item:last-child {
  margin-bottom: 0;
}

.summary-value {
  font-size: 36px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 5px;
}

.summary-label {
  font-size: 16px;
  color: #666;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }
  
  .right-column {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }
  
  .doctor-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .quick-stats {
    margin-top: 20px;
    width: 100%;
    justify-content: center;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
  
  .stats-content {
    flex-direction: column;
  }
  
  .stat-chart {
    padding-right: 0;
    margin-bottom: 30px;
  }
  
  .stat-summary {
    width: 100%;
    border-left: none;
    padding-left: 0;
    border-top: 1px solid #eee;
    padding-top: 30px;
    flex-direction: row;
    justify-content: space-around;
  }
  
  .summary-item {
    margin-bottom: 0;
  }
  
  .announcement-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-right {
    width: 100%;
    justify-content: space-between;
    margin-top: 5px;
  }
}
</style>